package com.base.util;

import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.mozilla.universalchardet.UniversalDetector;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 10进制和16进制的相互转换
 */
public class DecHexHelper {

    /**
     * 10进制int转16进制字符串
     *
     * @param decInt 10
     * @return A
     */
    public static String decInt2Hex(int decInt) {
        try {
            return Integer.toHexString(decInt).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 10进制int转16进制字符串
     *
     * @param decInt 10
     * @return 0A(不足偶数位前面补0)
     */
    public static String decInt2HexFormat(int decInt) {
        try {
            String hex = decInt2Hex(decInt);
            return hexFormat(hex).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 10进制字符串转16进制
     *
     * @param decValue 10进制字符串 "10"
     * @return 0A (不足偶数位的前面补0)
     */
    public static String decString2HexFormat(String decValue) {
        if (TextUtils.isEmpty(decValue))
            return "";
        int decInt = decParse(decValue);
        return decInt2HexFormat(decInt);
    }

    /**
     * 10进制字符串转16进制
     *
     * @param decValue 10进制字符串 "10"
     * @return 0A (不足偶数位的前面补0)
     */
    public static String decString2HexFormat(byte decValue) {
        if (0 == decValue)
            return "";
        int decInt = decParse(decValue);
        return decInt2HexFormat(decInt);
    }

    /**
     * 16进制格式化
     *
     * @param hexValue 16进制字符串
     * @return 不足偶数位的前面自动补0
     */
    public static String hexFormat(String hexValue) {
        if (TextUtils.isEmpty(hexValue))
            return "";
        if (hexValue.length() % 2 == 1) {
            return String.format("0%s", hexValue).toUpperCase();
        }
        return hexValue.toUpperCase();
    }

    /**
     * 将10进制字符串转换为10进制Int
     *
     * @param decValue 10进制字符串
     * @return 10进制Int
     */
    public static int decParse(String decValue) {
        return Integer.parseInt(decValue);
    }

    /**
     * 将10进制字符串转换为10进制Int
     *
     * @param decValue 10进制字符串
     * @return 10进制Int
     */
    public static int decParse(byte decValue) {
        return decValue;
    }

    /**
     * 16进制转10进制Int
     */
    public static int hex2DecInt(String hex) {
        if (TextUtils.isEmpty(hex))
            return 0;
        return Integer.parseInt(hex, 16);
    }

    /**
     * 16进制字符串转10进制byte
     */
    public static byte hex2DecByte(String hex) {
        //Integer.valueOf(hex, 16).byteValue();
        return (byte) Integer.parseInt(hex, 16);
    }

    /**
     * 16进制byte转16进制字符串
     */
    public static String hexByte2HexString(byte hexByte) {
        return Integer.toHexString(byteToInt(hexByte));
    }

    /**
     * @param decValue 待格式化的10进制数据
     * @return 格式化后的16进制数据(前低后高)
     */
    public static List<String> param2HexDataList(String decValue) {
        List<String> dataList = new ArrayList<>();
        if (TextUtils.isEmpty(decValue)) return dataList;

        int intValue = decParse(decValue);

        int low = 0xFF & intValue;
        String lowHex = decInt2HexFormat(low);
        dataList.add(lowHex);

        int high = (intValue >>> 8) & 0xFF;
        String highHex = decInt2HexFormat(high);
        dataList.add(highHex);

        return dataList;
    }

    /**
     * @param value  10进制数据
     * @param length 长度
     * @return byte[](前低后高)
     */
    public static List<Byte> reverseLowHigh(String value, int length) {
        int decValue = decParse(value);
        List<Byte> bytes = new ArrayList<>(length);
        for (int i = 0; i < length; i++) {
            byte v = intToByte((decValue >> (i * 8)) & 0xFF);
            bytes.add(v);
        }
        return bytes;
    }

    /**
     * 将前低后高byte数组转换为字符串
     *
     * @param byteData 前低后高数组
     */
    public static String reverseHighLow(List<Byte> byteData) {
        if (null == byteData || byteData.isEmpty())
            return "";
        StringBuilder builder = new StringBuilder();
        for (int i = byteData.size() - 1; i >= 0; i--) {
            byte hexByte = byteData.get(i);
            builder.append(hexByte2HexString(hexByte));
        }
        return builder.toString().toUpperCase();
    }

    /**
     * int转byte
     *
     * @param value 不能超过255，超过255后还原不回来
     */
    public static byte intToByte(int value) {
        return Integer.valueOf(value).byteValue();
    }

    public static byte stringToByte(String value) {
        return Integer.valueOf(value).byteValue();
    }

    public static int byteToInt(byte value) {
        return 0xFF & value;
    }

    /**
     * 16进制byte[]转16进制字符串
     */
    public static String byteArray2Hex(byte[] array) {
        //第1种方法
        StringBuilder hexBuilder = new StringBuilder();
        String tmp;
        for (byte b : array) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() % 2 == 1) {
                tmp = "0" + tmp;//只有一位的前面补个0
            }
            hexBuilder.append(tmp).append(" ");//每个字节用空格断开
        }
        return hexBuilder.toString().trim().toUpperCase();
    }

    /**
     * 16进制字符串转16进制byte[]
     */
    public static @Nullable
    byte[] hex2ByteArray(String hexStr) {
        if (TextUtils.isEmpty(hexStr)) {
            return null;
        }

        hexStr = hexStr.replace(" ", "");
        int length = hexStr.length();
        byte[] byteArray = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            int high = (Character.digit(hexStr.charAt(i), 16) << 4);
            int low = Character.digit(hexStr.charAt(i + 1), 16);
            byteArray[i / 2] = (byte) (high + low);
        }
        return byteArray;
    }

    /**
     * ascii转UTF8
     */
    public static @NonNull
    String byteArray2String(byte[] data) {
        if (null == data) {
            return "";
        }
        String byteString = Arrays.toString(data);
        if (TextUtils.isEmpty(byteString) || TextUtils.equals("null", byteString)) {
            return "";
        }
        try {
            String encode = getEncode(data);
            return new String(data, encode).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static boolean byteMatch(byte byteA, byte byteB) {
        return (byteA & 0xFF) == (byteB & 0xFF);
    }

    /**
     * 自动获取byte数组的编码格式
     */
    public static @NonNull
    String getEncode(byte[] bytes) {
        final String encode = "utf-8";
        try {
            UniversalDetector detector = new UniversalDetector(null);
            detector.handleData(bytes, 0, bytes.length);
            detector.dataEnd();
            String encoding = detector.getDetectedCharset();
            detector.reset();
            if (TextUtils.isEmpty(encoding)) {
                encoding = encode;
            }
            return encoding;
        } catch (Exception e) {
            return encode;
        }
    }
}
